//
//  UIImageView+QLXExt.m
//  fcuhConsumer
//
//  Created by 邱良雄 on 15/8/7.
//  Copyright (c) 2015年 avatar. All rights reserved.
//

#import "UIImageView+CYExt.h"
#import <Accelerate/Accelerate.h>
@implementation UIImageView(CYExt)

+ (instancetype)create{
    UIImageView * iv = [[self alloc] init];
    return iv;
}
+ (instancetype)createAspectFit{
    UIImageView * iv = [[self alloc] init];
    iv.contentMode = UIViewContentModeScaleAspectFit;
    return iv;
}
+ (instancetype)createAspectFill{
    UIImageView * iv = [[self alloc] init];
    iv.contentMode = UIViewContentModeScaleAspectFill;
    iv.clipsToBounds= YES;
    return iv;
}
+ (instancetype)createWithImageName:(NSString* ) name{
    UIImageView * iv = [[self alloc]initWithImage:[UIImage imageNamed:name]];
    return iv;
}

+ (instancetype)createWithAspectFitImageName:(NSString* )name{
    UIImageView * iv = [[self alloc]initWithImage:[UIImage imageNamed:name]];
    iv.contentMode = UIViewContentModeScaleAspectFit;
    return iv;
}

-(void) setImageWithURL:(NSString *) url placeholderImage:(UIImage *)placeholder animationType:(ImageViewAnimationType) type{
    NSURL * nUrl = [NSURL URLWithString:url];
    
    BOOL cached = [[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:url] != nil;
    
    [self sd_setImageWithURL:nUrl placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image && !error) {
            if (!cached) {
            }
            self.image = image;
        }
    }];
}

+(UIImage *)boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur
{
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 40);
    boxSize = boxSize - (boxSize % 2) + 1;
    CGImageRef img = image.CGImage;
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    void *pixelBuffer;
    //从CGImage中获取数据
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    //设置从CGImage获取对象的属性
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate( outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    //clean up CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    free(pixelBuffer);
    CFRelease(inBitmapData);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    return returnImage;
}

//- (void)xmg_setOriginImage:(NSString *)originImageURL thumbnailImage:(NSString *)thumbnailImageURL placeholder:(UIImage *)placeholder completed:(SDExternalCompletionBlock)completedBlock
//{
//    // 根据网络状态来加载图片
//    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
//
//    // 获得原图（SDWebImage的图片缓存是用图片的url字符串作为key）
//    UIImage *originImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:originImageURL];
//    if (originImage) { // 原图已经被下载过
//        [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:completedBlock];
//    } else { // 原图并未下载过
//        if (mgr.isReachableViaWiFi) {
//            [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:completedBlock];
//        } else if (mgr.isReachableViaWWAN) {
//            // 3G\4G网络下时候要下载原图
//            BOOL downloadOriginImageWhen3GOr4G = YES;
//            if (downloadOriginImageWhen3GOr4G) {
//                [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:completedBlock];
//            } else {
//                [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImageURL] placeholderImage:placeholder completed:completedBlock];
//            }
//        } else { // 没有可用网络
//            UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:thumbnailImageURL];
//            if (thumbnailImage) { // 缩略图已经被下载过
//                [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImageURL] placeholderImage:placeholder completed:completedBlock];
//            } else { // 没有下载过任何图片
//                // 占位图片;
//                [self sd_setImageWithURL:nil placeholderImage:placeholder completed:completedBlock];
//            }
//        }
//    }
//}
- (void)imageUrl:(NSString *)imageUrl placeholder:(UIImage *)placeholder
{
    [self sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:placeholder];
}

//- (void)setCircleHeader:(NSString *)headerUrl
//{
//    UIImage *placeholder = [UIImage xmg_circleImageNamed:@"defaultUserIcon"];
//    [self sd_setImageWithURL:[NSURL URLWithString:headerUrl] placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        // 图片下载失败，直接返回，按照它的默认做法
//        if (!image) return;
//        self.image = [image xmg_circleImage];
//    }];
//}

- (void)setHeader:(NSString *)headerUrl
{
    UIImage *placeholder = [UIImage imageNamed:@"bg_tx2"];
    [self sd_setImageWithURL:[NSURL URLWithString:headerUrl] placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        // 图片下载失败，直接返回，按照它的默认做法
        if (!image) return;
        self.image = image;
    }];
}

@end
